<template>
	<view class="content">
		<projectSelect @go='go'></projectSelect>
		<view class="question-wrap">
			<view class="question-container">
				<view class="question">
					<view class="iconfont icon-wentijieda"></view>
					<text class="text">问题</text>
				</view>
			</view>
		</view>
		<view class="query">
			<view class="btn" @click="handleShowQuestion()">
				<text class="iconfont icon-jiahao"></text> 添加
			</view>
		</view>
		<view class="footer">
			<view class="record" @click="getHistory">
				<view class="iconfont icon-lishijilu_huaban"></view>
				<text>历史记录</text>
			</view>
			<view class="submit">
				提交检查
			</view>
		</view>
		<u-popup mode="center" :show="showQuestion" @close="closeQuestionPop" :round="50">
			<view class="pop project-pop">
				<view class="title">
					<text>问题详情</text>
				</view>
				<view class="body">
					<view class="wrapper _scroll">
						<view class="section-1">
							<view class="form-item upload-wrap">
								<view class="label">现场照片</view>
								<u-upload :fileList="fileList" :previewFullImage="true" @afterRead="afterRead"
									@delete="deletePic" multiple :maxCount="1"
									:style="{position:'relative',height:fileList.length == 0 ? '44rpx' : 'unset',border: fileList.length == 0 ? 'solid 2rpx #1534ce' : 'none', borderRadius: '20rpx'}">
									<view class="iconfont icon-tupian"></view>
								</u-upload>
							</view>
							<view class="form-item">
								<view class="label">问题描述</view>
								<view class="input">
									<u--input placeholderClass="input-placeholder" class="input-body"
										placeholder="请输入问题描述" v-model="form.check_content"></u--input>
								</view>
							</view>
							<view class="form-item">
								<view class="label">问题类型</view>
								<u-radio-group v-model="form.check_type_name" @change="groupChange"
									iconPlacement="left">
									<u-radio v-for="(item, index) in radiolist" :key="index" :label="item.name"
										:name="item.name" @change="radioChange" activeColor="#1534ce" iconSize="8"
										size="12">
									</u-radio>
								</u-radio-group>
							</view>
							<view class="form-item">
								<view class="label">违章库</view>
								<view class="input" @click="showPeccancy = true">
									<u--input placeholderClass="input-placeholder" class="input-body"
										placeholder="请选择违章库" readonly v-model="form.peccancy_content"></u--input>
								</view>
							</view>
							<view class="form-item">
								<view class="label">责任人</view>
								<view class="input" @click="showUser = true">
									<u--input placeholderClass="input-placeholder" class="input-body"
										placeholder="请输入责任人" v-model="form.zrr_name"></u--input>
								</view>
							</view>
							<view class="form-item">
								<view class="label">罚款</view>
								<view class="input">
									<u--input placeholderClass="input-placeholder" class="input-body"
										placeholder="请输入罚款" v-model="form.fk_money"></u--input>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="custom-button" @click="submit">
					确认
				</view>
			</view>
		</u-popup>
		<u-popup mode="center" :show="showHistory" @close="showHistory = false" :round="50">
			<view class="pop problem-pop">
				<view class="title">
					<text>历史记录</text>
				</view>
				<view class="body">
					<mescroll-uni ref="mescrollRef" height='100%' @init="mescrollInit" @up="upCallback" :up="upOption" :down="{use: false}">
						<view class="problem-list">
							<view class="item" v-for="item in hostoryList">
								<view class="project">{{item.code}}.{{item.project_name}}</view>
								<view class="img">
									<image mode="aspectFill" :src="item.file_path"></image>
									<view class="problem-title">{{item.check_content}}</view>
								</view>
								<view class="info">
									<view class="info-item">
										<view class="label">类型</view>
										<view class="value">{{item.check_type == 1 ? '质量问题' : '安全问题'}}</view>
									</view>
									<view class="info-item">
										<view class="label">违章库</view>
										<view class="value">{{item.peccancy_type}}</view>
									</view>
									<view class="info-item">
										<view class="label">责任人</view>
										<view class="value">{{item.zrr_name}}</view>
									</view>
									<view class="info-item">
										<view class="label">罚款</view>
										<view class="value">{{item.fk_money}}</view>
									</view>
								</view>
							</view>
						</view>
					</mescroll-uni>
				</view>
			</view>
		</u-popup>
		<u-popup mode="center" :show="showPeccancy" @close="closePeccancy" :round="50">
			<view class="pop user-pop">
				<view class="title">
					<text>请选择违章库</text>
				</view>
				<view class="body">
					<view class="wrapper _scroll">
						<view class="item" v-for="(item, idx) in peccancyList" :key="idx"
					  @click="handleSelectPeccancy(idx)">
							<view :class="`check ${selectedPeccancy.indexOf(idx) !== -1 ? 'check__active' : ''}`">
								<view class="check-on"></view>
							</view>
							<view class="name">{{item.peccancy_content}}</view>
						</view>
					</view>
				</view>
				<view class="custom-button" @click="confirmSelectPeccancy()">
					确认（{{selectedPeccancy.length}}）
				</view>
			</view>
		</u-popup>
		<u-popup mode="center" :show="showUser" @close="closeUserPop" :round="50">
			<view class="pop user-pop">
				<view class="title">
					<text>请选择责任人</text>
				</view>
				<view class="body">
					<view class="wrapper">
						<u-index-list :indexList="indexList">
							<view slot="header" class="list">
								<u-line></u-line>
							</view>
							<template v-for="(item, key, index) in userIndexList">
								<u-index-item :key="item + index">
									<u-index-anchor :text="key"></u-index-anchor>
									<view class="list" v-for="(item1, index1) in item" :key="item1 + index1" @click="handleSelectUser(item1.user_id)">
										<view class="item" >
											<view 
											:class="`check ${selectedUser.indexOf(item1.user_id) !== -1 ? 'check__active' : ''}`" 
											>
												<view class="check-on"></view>
											</view>
											<view class="name">{{item1.nick_name}}</view>
										</view>
										<u-line></u-line>
									</view>
								</u-index-item>
							</template>
						</u-index-list>
					</view>
				</view>
				<view class="custom-button" @click="confirmSelectUser()">
					确认（{{selectedUser.length}}）
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import Pinyin from '@/src/utils/ChinesePY.js'
	const indexList = () => {
		const indexList = []
		const charCodeOfA = 'A'.charCodeAt(0)
		for (let i = 0; i < 26; i++) {
			indexList.push(String.fromCharCode(charCodeOfA + i))
		}
		return indexList
	}
	import {
		userListApi
	} from '@/api/user.js'
	import {
		addProject,
		getViolation
	} from '@/api/patrol.js';
	import {
		checkListApi
	} from '@/api/statistics.js'
	import {
		mapGetters
	} from 'vuex';
	import projectSelect from '@/components/project_select/index.vue'
	import { uploadUrl } from '@/baseUrl.js';
	export default {
		components: {
			projectSelect
		},
		computed: {
			...mapGetters({
				curProject: 'system/getCurProject',
				userInfo: 'system/getUserInfo'
			})
		},
		data() {
			return {
				indexList: indexList(),
				checked: false,
				mescroll: null, // mescroll实例对象 (此行可删,mixins已默认)
				upOption: {
					textNoMore: '-- 没有更多了 --'
				},
				pageSize: 20,
				fileList: [],
				showQuestion: false,
				radiolist: [{
						name: '质量问题',
						disabled: false
					},
					{
						name: '安全问题',
						disabled: false
					}
				],
				form: {
					check_type_name: '质量问题',
					check_content: '',
					zrr_name: '',
					fk_money: '',
					peccancy_content: ''
				},
				showPeccancy: false,
				showHistory: false,
				peccancyList: [],
				hostoryList: [],
				userList: [],
				showUser: false,
				selectedUser: [],
				selectedPeccancy: [],
				indexList: indexList(),
				userIndexList: {}
			};
		},
		methods: {
			go() {
				
			},
			confirmSelectUser() {
				if (!this.selectedUser.length){
					this.closeUserPop(); 
					return;
				}
				let str = this.userList
					.filter((item, idx) => this.selectedUser.indexOf(item.user_id) !== -1)
					.map(item => item.nick_name)
					.join(',');
				this.form.zrr_name = str;
				this.closeUserPop();
			},
			handleSelectAll(e) {
				if (e) {
					this.selectedUser = this.userList.map(item => item.user_id);
				} else {
					this.selectedUser = [];
				}
			},
			closePeccancy() {
				this.showPeccancy = false;
			},
			closeUserPop() {
				this.showUser = false;
			},
			handleSelectUser(idx) {
				this.selectedUser = [idx];
			},
			handleSelectPeccancy(idx) {
				this.selectedPeccancy = [idx];
			},
			confirmSelectPeccancy() {
				if (!this.selectedPeccancy.length){
					this.closePeccancy(); 
					return;
				}
				let item = this.peccancyList
					.filter((item, idx) => this.selectedPeccancy.indexOf(idx) !== -1)[0];
				this.form.peccancy_id = item.id
				this.form.peccancy_content = item.peccancy_content;
				this.closePeccancy();
			},
			user_id() {
				if (!this.selectedUser.length){
					this.closeUserPop(); 
					return;
				}
				let str = this.userList
					.filter((item) => this.selectedUser.indexOf(item.user_id) !== -1)
					.map(item => item.nick_name)
					.join(',');
				this.form.zrr_name = str;
				this.closeUserPop();
			},
			handleShowQuestion() {
				this.showQuestion = true;
				this.fetchUser();
				this.handleGetViolation();
			},
			async fetchUser() {
				uni.showLoading({title: '加载中...'});
				const { data } = await userListApi();
				uni.hideLoading();
				if (data.code === 1) {
					let arr = data.data.list;
					let map = {};
					this.indexList.forEach(item => {
						map[item] = [];
					})
					arr.forEach(item => {
						const first = Pinyin.getWordsCode(item.nick_name).toUpperCase().substring(0, 1);
						if (!map[first]) {
							map[first] = [];
						}
						map[first].push(item);
					})					
					this.userIndexList = map;
					this.userList = data.data.list;
				}
				
			},
			async handleGetViolation() {
				uni.showLoading({
					title: '加载中...'
				});
				const {
					data
				} = await getViolation();
				uni.hideLoading();
				if (data.code === 1) {
					this.peccancyList = data.data
				}
			},
			getHistory() {
				this.showHistory = true
			},
			/*mescroll组件初始化的回调,可获取到mescroll对象 (此处可删,mixins已默认)*/
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},

			/*上拉加载的回调*/
			async upCallback(page) {
				const {
					data
				} = await checkListApi({
					project_id: this.curProject.id,
					pageSize: this.pageSize,
					page: page.num
				});
				if (data.code === 1 || data.code === 200) {
					// 接口返回的当前页数据列表 (数组)
					let curPageData = data.data.data;
					curPageData.forEach((item, idx) => {
						curPageData[idx].code = idx + 1 + (page.num - 1) * this.pageSize
					});
					// 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
					let curPageLen = curPageData.length;
					// 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
					let totalPage = data.data.last_page;
					//设置列表数据
					if (page.num == 1) this.hostoryList = []; //如果是第一页需手动置空列表
					this.hostoryList = this.hostoryList.concat(curPageData); //追加新数据
					// 请求成功,隐藏加载状态
					//方法一(推荐): 后台接口有返回列表的总页数 totalPage
					this.mescroll.endByPage(curPageLen, totalPage);
					setTimeout(() => {
						this.mescroll.endSuccess(curPageLen)
					}, 20)
				} else {
					//  请求失败,隐藏加载状态
					this.mescroll.endErr()
				}
			},
			groupChange(n) {
				console.log('groupChange', n);
			},
			radioChange(n) {
				console.log('radioChange', n);
			},
			// 删除图片
			deletePic(event) {
				this[`fileList`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList`].length
				lists.map((item) => {
					this[`fileList`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList`][fileListLen]
					this[`fileList`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.data.file_id
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uploadUrl, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
			submit() {
				this.form.project_id = this.curProject.id
				this.form.check_type = this.form.check_type_name == '质量问题' ? 1 : 2
				this.form.check_photo = this[`fileList`].length > 0 ? this[`fileList`][0].url : ''
				this.form.check_user = this.userInfo.nick_name
				if (![1, 2].includes(this.form.check_type)) {
					uni.showToast({
						title: '请选择问题类型',
						duration: 1000,
						icon: 'error'
					});
					return
				}
				if (this.form.fk_money == '') {
					uni.showToast({
						title: '请输入罚款',
						duration: 1000,
						icon: 'error'
					});

					return
				}
				uni.showLoading({
					title: '加载中...'
				});
				addProject({
					...this.form
				}).then(res => {
					if (res.data.code == 1 || res.data.code == 200) {

						uni.showToast({
							title: '操作成功',
							duration: 1000,
							icon: 'success'
						});
						for (let key in this.form) {
							this.form[key] = ''
						}
						this.showQuestion = false
						uni.hideLoading();
					} else {
						uni.showToast({
							title: '操作失败',
							duration: 1000,
							icon: 'error'
						});
						uni.hideLoading();
					}
				})
			},
			closeQuestionPop() {
				this.showQuestion = false
			}
		},
	}
</script>

<style scoped lang="scss">
	.actions{
		width: 100%;
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 0px 25px;
		.checkbox{
			font-size: 26rpx;
			font-weight: normal;
			font-stretch: normal;
			letter-spacing: 8rpx;
			color: #333;
			width: 200rpx;
			padding-top: calc((62rpx - 18px) / 2);
		}
	}
	/deep/{
		.u-index-list__letter__item__index{
			color: #fff!important;
		}
	}
	/deep/ .uni-picker-view-content>* {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		padding: 0 10rpx;
		width: calc(100% - 20rpx);
	}

	/deep/ .uni-picker-view-content>* {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		padding: 0 10rpx;
		width: calc(100% - 20rpx);
	}

	.user-pop {
		.body{
			padding: 40rpx 50rpx;
			.wrapper{
				width: 100%;
				height: 540rpx;
				overflow-y: auto;
				overflow-x: hidden;
			}
			.item{
				width: auto;
				@include clear();
				.check{
					width: 24rpx;
					height: 24rpx;
					border: solid 1rpx #000000;
					border-radius: 50%;
					float: left;
					margin-top: 16rpx;
					position: relative;
					.check-on{
						transition: 0.3s ease;
						opacity: 0;
						transform: scale(0.5);
						border-radius: 50%;
						position: absolute;
						top: 0;
						left: 0;
						right: 0;
						bottom: 0;
						margin: auto;
						width: 18rpx;
						height: 18rpx;
						background-color: #000000;
					}
				}
				.name{
					float: left;
					width: calc(100% - 24rpx - 40rpx);
					font-size: 26rpx;
					font-weight: 300;
					padding: 15rpx 0;
					font-stretch: normal;
					line-height: 30rpx;
					letter-spacing: 0rpx;
					color: #000000;
					margin-left: 20rpx;
				}
				.check__active{
					.check-on{
						opacity: 1;
						transform: scale(1);
					}
				}
			}
		}
	}

	.problem-pop {
		height: 70vh;

		// overflow-y: auto !important;
		.body {
			height: calc(100% - 96rpx);
			overflow-y: auto !important;

		}
	}

	.problem-list {
		width: 100%;

		.item {
			border-bottom: solid 2rpx #e2e7f5;
			padding: 0 35rpx;
			box-sizing: border-box;
		}

		.project {
			font-size: 26rpx;
			font-weight: normal;
			font-stretch: normal;
			line-height: 36rpx;
			letter-spacing: 0rpx;
			color: #000000;
			margin-top: 20rpx;
			margin-bottom: 10rpx;
		}

		.img {
			width: 100%;
			height: 248rpx;
			background-color: #000000;
			position: relative;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;

			}

			.problem-title {
				position: absolute;
				left: 0;
				bottom: 0;
				width: 100%;
				height: 65rpx;
				background-color: rgba(0, 0, 0, 0.7);
				text-align: center;
				line-height: 65rpx;
				font-size: 26rpx;
				font-weight: normal;
				font-stretch: normal;
				letter-spacing: 3rpx;
				color: #ffffff;
				text-overflow: ellipsis;
				overflow: hidden;
				white-space: nowrap;
			}
		}

		.info {
			margin-top: 15rpx;
			margin-bottom: 30rpx;
			@include clear();

			.info-item {
				float: left;
				width: 25%;

				.label {
					height: 30rpx;
					font-family: SourceHanSansCN-Regular;
					font-size: 16rpx;
					font-weight: normal;
					font-stretch: normal;
					line-height: 30rpx;
					letter-spacing: 0rpx;
					color: #8497ac;
					margin-bottom: 3rpx;
				}

				.value {
					font-size: 26rpx;
					font-weight: bold;
					font-stretch: normal;
					line-height: 34rpx;
					letter-spacing: 0rpx;
					color: #46464a;
				}

				.content {
					font-size: 26rpx;
					font-weight: bold;
					font-stretch: normal;
					line-height: 34rpx;
					letter-spacing: 0rpx;
					color: #46464a;
				}
			}
		}

	}

	.content {
		width: 100%;
		background-color: #2e5efe;
		position: relative;

		.pop {
			width: 671rpx;
			padding-bottom: 40rpx;
			background-color: #fff;
			-webkit-border-radius: 35rpx;
			-moz-border-radius: 35rpx;
			border-radius: 35rpx;
			overflow: hidden;

			/deep/ .mescroll-uni-fixed {
				position: inherit;
			}

			.title {
				width: 100%;
				height: 96rpx;
				line-height: 96rpx;
				background-color: #1534ce;
				font-size: 42rpx;
				font-weight: normal;
				font-stretch: normal;
				letter-spacing: 4rpx;
				color: #ffffff;
				text-align: center;
			}

		}

		.section-1 {
			width: 100%;
			border-radius: 50rpx;
			background-color: #fafbfd;
			padding-top: 50rpx;
			padding-bottom: 20rpx;
			box-shadow: 0rpx -10rpx 29rpx 8rpx rgba(#bcbcb5, 0.19);
			position: relative;
			top: 0;

			.form-item {
				width: 600rpx;
				height: 48rpx;
				line-height: 48rpx;
				margin: 0 auto;
				margin-bottom: 25rpx;
				display: flex;
				align-items: center;

				&:last-child {
					margin-bottom: 34rpx;
				}

				&.upload-wrap {
					align-items: unset;
					height: unset;
					line-height: unset;
				}

				@include clear();

				.label {
					float: left;
					width: 130rpx;
					height: 48rpx;
					text-align: left;
					line-height: 44rpx;
					font-size: 26rpx;
					color: #46464a;
				}

				/deep/ .u-upload__wrap {
					width: calc(100% - 206rpx) !important;
					background-color: transparent;
				}

				.icon-tupian {
					position: absolute;
					right: 25rpx;
					line-height: 44rpx;
					color: #1534ce;
					font-size: 28rpx;
				}

				/deep/ .u-radio-label--left {
					margin-right: 55rpx;
				}

				/deep/ .u-radio__text {
					font-size: 26rpx !important;
					color: #46464a !important;
				}

				.input {
					float: left;
					width: calc(100% - 134rpx - 3rpx);
					border-radius: 20rpx;
					border: solid 2rpx #1534ce;

					.input-body {
						box-sizing: border-box;
						width: 100%;
						height: 44rpx;
						padding: 0 !important;
						border: none;
						padding-left: 30rpx !important;
						padding-right: 30rpx !important;
						font-size: 26rpx;
						font-weight: normal;
						font-stretch: normal;
						letter-spacing: 0rpx;
						color: rgba(0, 0, 0, 0.7);
					}

					.input-placeholder {
						font-size: 26rpx;
						font-weight: normal;
						font-stretch: normal;
						letter-spacing: 0rpx;
						color: rgba(0, 0, 0, 0.5);
					}
				}
			}
		}

		.footer {
			box-shadow: 0 0 20rpx 10rpx rgba(#bcbcb5, 0.17);
			width: 100%;
			height: 150rpx;
			background-color: #ffffff;
			position: fixed;
			bottom: 0;
			left: 0;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.record {
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;

				.icon-lishijilu_huaban {
					font-size: 43rpx;
					color: #3b3c40;
				}

				text {
					font-size: 26rpx;
					color: #3b3c40;
					margin-top: 10rpx;
				}
			}

			.submit {
				width: 287rpx;
				height: 83rpx;
				background-color: #1534ce;
				border-radius: 20rpx;
				letter-spacing: 14rpx;
				color: #ffffff;
				font-size: 26rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.query {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background: #fff;
			padding-right: 41rpx;

			.btn {
				text-align: center;
				width: 176rpx;
				height: 60rpx;
				background-color: #1534ce;
				border-radius: 30rpx;
				font-size: 26rpx;
				font-weight: normal;
				font-stretch: normal;
				line-height: 60rpx;
				letter-spacing: 6rpx;
				color: #ffffff;

				.iconfont {
					font-size: 26rpx;
					line-height: 60rpx;
				}

			}
		}

		.question-wrap {
			width: 100%;
			background-color: #1332cd;

			.question-container {
				width: 100%;
				background-repeat: no-repeat;
				border-top-left-radius: 50rpx;
				border-top-right-radius: 50rpx;
				overflow: hidden;
				box-sizing: border-box;
				background-color: #fff;
				padding: 27rpx 0rpx;
				@include clear();
			}

			.question {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				border-bottom: 2rpx solid #1534ce;
				padding-bottom: 26rpx;
				padding-left: 41rpx;

				.icon-wentijieda {
					font-size: 26rpx;
				}

				.text {
					color: #46464a;
					font-size: 26rpx;
					margin-left: 12rpx;
				}
			}
		}

		.address-wrap {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			background: #1c32c5;
			border-radius: 49rpx 49rpx 0 0;
			padding: 35rpx 40rpx 65rpx;

			.icon-qiehuan {
				color: #fff;
				font-size: 27rpx;
			}

			.text {
				font-size: 26rpx;
				color: #fff;
				margin-left: 21rpx;
				text-overflow: ellipsis;
				overflow: hidden;
				white-space: nowrap;
			}
		}
	}
</style>
